import React from 'react'
import { useDispatch } from 'react-redux'
import { setInputValue } from '../store/todoSlice'

// 待办事项输入框组件，受控组件，支持新增和编辑

export interface Props {
  onAdd: (text: string) => void
  value: string
  setValue: (v: string) => void
  isEditing?: boolean
}

const TodoInput: React.FC<Props> = ({ onAdd, value, setValue }) => {
  const dispatch = useDispatch()
  const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
    // handleKeyDown: 监听回车，触发新增或编辑
    if (e.key === 'Enter' && value.trim()) {
      onAdd(value.trim())
      // 输入框清空由父组件控制
    }
  }

  return (
    <input
      className="todo-input"
      placeholder=""
      value={value}
      onChange={e => { setValue(e.target.value); dispatch(setInputValue(e.target.value)) }}
      onKeyDown={handleKeyDown}
    />
  )
}

export default TodoInput